<template>
  <RkContainer :isFooter="false"
    :isAside="false">
    <template #header_left>
    </template>
    <template #header_right>
      <el-button type="primary"
        @click="handelEdit('add')">添加</el-button>
      <el-button @click="handleOperation('start','启用',1)">启用</el-button>
      <el-button @click="handleOperation('cancle','停用',0)">停用</el-button>
      <el-button type="danger"
        @click="handleOperation('delete', '删除')">删除</el-button>
    </template>
    <template #main>
      <rk-center>
        <template #content>
          <rk-grid ref="agencyManageViewRef"
            :title="route.meta.title"
            dataUrl="/thirdAgency/getAgencyGridPage"
            boxConfig
            :params="queryParams"
            :columns="tableColumns">
            <template #toolbar_title_buttons>
              <!-- <AdTreeSelect v-model="queryParams.adCode"
                placeholder="请选择区划"
                style="width: 200px;margin-right: 12px;"
                @change="handleSearch">
              </AdTreeSelect> -->
              <el-input v-model="queryParams.agencyName"
                placeholder="请输入机构名称"
                class="w-200px"
                clearable
                @input="handleSearch" />
            </template>
            <template #operation="{ row }">
              <div style="display: flex; justify-content: space-between;">
                <el-button type="primary"
                  link
                  @click="handelEdit('edit',row)">修改</el-button>
                <el-button type="primary"
                  link
                  @click="handleOpenAgencyCount(row,'edit')">{{ route.query.type === '1' ? '机构用户' : '用户' }}</el-button>
                <el-button type="primary"
                  link
                  v-if="route.query.type === '1'"
                  @click="handleEaraOpenRegion(row,'edit')">管辖地区</el-button>
              </div>
            </template>
            <template #user_count="{ row, column }">
              <a v-if="row[column.field]>0"
                class="yhs-pro-name-no-underline"
                href='javascript:;'
                @click="handleOpenAgencyCount(row,'detail')">{{
                                row[column.field] || '—' }}</a>
              <span v-else>{{ row[column.field] }}</span>
            </template>
            <template #region_count="{ row, column }">
              <a v-if="row[column.field]>0"
                class="yhs-pro-name-no-underline"
                href='javascript:;'
                @click="handleEaraOpenRegion(row,'detail')">{{
                                row[column.field] || '—' }}</a>
              <span v-else>{{ row[column.field] }}</span>
            </template>
          </rk-grid>
        </template>
      </rk-center>
    </template>
    <organize-info-dialog ref="organizationInforDialogRef"
      :title="inforTitle + title"
      :formCode="route.query.formCode"
      @refresh="handleRefresh"></organize-info-dialog>
    <agency-user ref="agencyUserref"
      @refresh="handleSearch"></agency-user>
  </RkContainer>
</template>
<script setup >
import { ElLoading } from "element-plus"
import { useRoute } from 'vue-router'
import { RkConfirmBox } from '@/components/message-box/index.js'
import { OrganizeInfoDialog } from '@/components/dialog';
import AgencyUser from './dialogs/AgencyUser.vue'
import { useAgencyApi } from '@/api'
const { deleteThirdAgency, updateAgencyStatus } = useAgencyApi

const { appContext } = getCurrentInstance();
const globalProxy = appContext.config.globalProperties;
const agencyUserref = ref(null)
let route = useRoute()
const title = ref('')
const organizationType = ref('1')
// 查询参数
let queryParams = reactive({
  type: route.query.type,
  agencyName: undefined,
  adCode: undefined
})
if (route.query.type === '1') {
  title.value = '机构信息'
} else if (route.query.type === '2') {
  title.value = '会计事务所信息'
} else {
  title.value = '律师事务所信息'
}
organizationType.value = queryParams.type
const organizationInforDialogRef = ref(null)
const agencyManageViewRef = ref(null)
const tableColumns = ref([
  { field: 'statusName', title: '状态', width: 80, align: 'center' },
  { field: 'code', title: '编码', width: 200, align: 'left', },
  {
    field: 'name',
    title: '名称',
    width: 250,
    align: 'left',
  },
  // { field: 'userCount', title: route.query.type === '1' ? '机构用户数量' : '用户数量', width: 150, align: 'center', slots: { default: 'user_count' } },
  // { field: 'regionCount', title: '机构区划数量', width: 150, align: 'center', visible: route.query.type === '1' ? true : false, slots: { default: 'region_count' } },
  { field: 'uscc', title: '统一社会信用代码', width: 250, align: 'left' },
  { field: 'userCount', title: route.query.type === '1' ? '机构用户' : '用户', width: 150, align: 'center', slots: { default: 'user_count' } },
  { field: 'regionCount', title: '管辖地区', width: 150, align: 'center', visible: route.query.type === '1' ? true : false, slots: { default: 'region_count' } },
  { field: 'year', title: '年度', width: 120, align: 'center', },
  { field: 'startDate', title: '起始时间', width: 120, align: 'center' },
  { field: 'endDate', title: '终止时间', width: 120, align: 'center' },
  { field: "operation", title: "操作", width: route.query.type === '1' ? 200 : 100, align: 'center', fixed: 'right', slots: { default: 'operation' } }
])
/**查询 */
const handleSearch = () => {
  agencyManageViewRef.value.searchEvent()
}

//打开机构用户
const handleOpenAgencyCount = (row, dialogType) => {
  if (route.query.type === '1') {
    agencyUserref.value.handleOpen('agency', row, dialogType)
  } else {
    agencyUserref.value.handleOpen('user', row, dialogType)
  }
}

//打开区划
const handleEaraOpenRegion = (row, dialogType) => {
  agencyUserref.value.handleOpen('area', row, dialogType)
}

//启用、停用、删除
const handleOperation = async (buttonType, textName, status) => {
  const seleRows = agencyManageViewRef.value.getCheckboxRecords()
  if (seleRows.length == 0 || !seleRows) {
    globalProxy.$message({ message: `请至少选择一条数据进行${textName}！`, type: "warning" });
    return;
  }
  if (buttonType == 'edit') { //修改
  } else {
    RkConfirmBox({
      title: '提示',
      content: `您确定要${textName}吗？`,
      onSubmit: async function () {
        //获取选中数据
        const agencyArray = []
        seleRows.forEach(element => {
          agencyArray.push(element.agencyId)
        });
        const agencyIds = agencyArray.join(',')
        const loading = ElLoading.service({ fullscreen: true })
        if (buttonType == 'delete') {  //删除
          const params = { agencyIds }
          const result = await deleteThirdAgency(params)
          const { data, code, msg } = result
          if (code === 200) {
            loading.close()
            globalProxy.$message({ message: `${textName}成功！`, type: "success" });
            handleSearch()
          } else {
            loading.close()
            globalProxy.$message({ message: `${msg}`, type: "error" });
          }
        } else if (buttonType == 'start' || buttonType == 'cancle') { //启用
          const params = { agencyIds, status }
          const result = await updateAgencyStatus(params)
          const { data, code, msg } = result
          if (code === 200) {
            loading.close()
            globalProxy.$message({ message: `${textName}成功！`, type: "success" });
            handleSearch()
          } else {
            loading.close()
            globalProxy.$message({ message: `${msg}`, type: "error" });
          }
        }
      },
      onCancel: function () {
      }
    })
  }
}

//新增项目
const inforTitle = ref('编辑')
const handelEdit = (type, row) => {
  let organizationType = queryParams.type
  if (type == 'add') {
    inforTitle.value = '添加'
    organizationInforDialogRef.value.handleAdd({ organizationType })
  } else if (type == 'edit') {
    inforTitle.value = '编辑'
    const agencyId = row.agencyId
    organizationInforDialogRef.value.handleEdit({ agencyId, organizationType })
  }
}

const handleRefresh = () => {
  handleSearch()
}

</script>
  
<style lang="scss" scoped>
.w-200px {
	width: 200px;
}
.agency-mange-table {
	display: flex;
	height: 100%;
}
.user-table {
	flex: 1;
	border-right: 2px solid #efefef;
	width: 50%;
}
</style>
  